'use client';

import { useState, useEffect } from 'react';
import { FamilyMember } from '../types/family';
import { convertToAncientNumber } from '../types/ancientNumberMap';

interface PersonFormProps {
  familyData: FamilyMember[];
  onSubmit: (person: Omit<FamilyMember, 'id'>) => void;
  onCancel: () => void;
}

export default function PersonForm({ familyData, onSubmit, onCancel }: PersonFormProps) {
  const [formData, setFormData] = useState({
    name: '',
    gender: 'male' as 'male' | 'female',
    parentId: '',
    ranking: '',
    birthDate: '',
    deathDate: '',
    generation: 1,
    biography: '',
    spouseName: '',
    spouseBirthDate: '',
    spouseDeathDate: '',
    spouseBiography: '',
   
    town: '',
    county: '',
    notes: ''
  });

  // 当选择父母时自动计算世次
  useEffect(() => {
    if (formData.parentId) {
      const parent = familyData.find(p => p.id === formData.parentId);
      if (parent) {
        setFormData(prev => ({ ...prev, generation: parent.generation + 1 }));
      }
    }
    // 如果没有选择父母，不自动设置世次，保持用户输入的值
  }, [formData.parentId, familyData]);

  // 当性别变化时清空排名选择
  useEffect(() => {
    setFormData(prev => ({ ...prev, ranking: '' }));
  }, [formData.gender]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit(formData);
    setFormData({
      name: '',
      gender: 'male' as 'male' | 'female',
      parentId: '',
      ranking: '',
      birthDate: '',
      deathDate: '',
      generation: 1,
      biography: '',
      spouseName: '',
      spouseBirthDate: '',
      spouseDeathDate: '',
      spouseBiography: '',
   
      town: '',
      county: '',
      notes: ''
    });
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'number' ? parseInt(value) || 0 : value
    }));
  };

  return (
    <div className="bg-white rounded-lg shadow-lg p-6">
      <h2 className="text-2xl font-bold text-secondary mb-6">添加族谱成员</h2>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              姓名 <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              name="name"
              value={formData.name}
              onChange={handleChange}
              required
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>



          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              何人子女
            </label>
            <select
              name="parentId"
              value={formData.parentId}
              onChange={handleChange}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
            >
              <option value="">选择父母</option>
              {familyData.map(person => (
                <option key={person.id} value={person.id}>
                  {person.name} (第{convertToAncientNumber(person.generation)}世)
                </option>
              ))}
            </select>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-3">
            性别 <span className="text-red-500">*</span>
          </label>
          <div className="flex gap-6">
            <label className="flex items-center space-x-2 cursor-pointer">
              <input
                type="radio"
                name="gender"
                value="male"
                checked={formData.gender === 'male'}
                onChange={handleChange}
                required
                className="w-4 h-4 text-primary border-gray-300 focus:ring-primary focus:ring-2"
              />
              <span className="text-sm text-gray-700">男</span>
            </label>
            <label className="flex items-center space-x-2 cursor-pointer">
              <input
                type="radio"
                name="gender"
                value="female"
                checked={formData.gender === 'female'}
                onChange={handleChange}
                required
                className="w-4 h-4 text-primary border-gray-300 focus:ring-primary focus:ring-2"
              />
              <span className="text-sm text-gray-700">女</span>
            </label>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-3">
            排名<span className="text-red-500">*</span>
          </label>
          <div className="flex flex-wrap gap-4">
            {(formData.gender === 'male'
              ? ['长子', '次子', '三子', '四子', '五子', '六子', '七子', '八子', '九子', '十子']
              : ['长女', '次女', '三女', '四女', '五女', '六女', '七女', '八女', '九女', '十女']
            ).map((rank) => (
              <label key={rank} className="flex items-center space-x-2 cursor-pointer">
                <input
                  type="radio"
                  name="ranking"
                  value={rank}
                  checked={formData.ranking === rank}
                  onChange={handleChange}
                  className="w-4 h-4 text-primary border-gray-300 focus:ring-primary focus:ring-2"
                />
                <span className="text-sm text-gray-700">{rank}</span>
              </label>
            ))}
          </div>
        </div>




        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              出生年月日
            </label>
            <input
              type="date"
              name="birthDate"
              value={formData.birthDate}
              onChange={handleChange}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              终年月日
            </label>
            <input
              type="date"
              name="deathDate"
              value={formData.deathDate}
              onChange={handleChange}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            世次
          </label>
          <input
            type="number"
            name="generation"
            value={formData.generation}
            onChange={handleChange}
            min="1"
            readOnly={!!formData.parentId}
            className={`w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary ${formData.parentId ? 'bg-gray-100 cursor-not-allowed' : ''
              }`}
          />
          <p className="text-xs text-gray-500 mt-1">
            {formData.parentId ? '选择父母后自动计算' : '可手工输入世次'}
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            履历
          </label>
          <textarea
            name="biography"
            value={formData.biography}
            onChange={handleChange}
            rows={3}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            配偶姓名
          </label>
          <input
            type="text"
            name="spouseName"
            value={formData.spouseName}
            onChange={handleChange}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              配偶出生年月日
            </label>
            <input
              type="date"
              name="spouseBirthDate"
              value={formData.spouseBirthDate}
              onChange={handleChange}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              配偶终年月日
            </label>
            <input
              type="date"
              name="spouseDeathDate"
              value={formData.spouseDeathDate}
              onChange={handleChange}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            配偶履历
          </label>
          <textarea
            name="spouseBiography"
            value={formData.spouseBiography}
            onChange={handleChange}
            rows={3}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>

    

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">

          <label className="block text-sm font-medium text-gray-700 mb-1">
            住址
          </label>
          <p />
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              镇(市)
            </label>
            <input
              type="text"
              name="town"
              value={formData.town}
              onChange={handleChange}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              区(县或村)
            </label>
            <input
              type="text"
              name="county"
              value={formData.county}
              onChange={handleChange}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            备注
          </label>
          <textarea
            name="notes"
            value={formData.notes}
            onChange={handleChange}
            rows={3}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>

        <div className="flex justify-end space-x-4 pt-4">
          <button
            type="button"
            onClick={onCancel}
            className="px-6 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors"
          >
            取消
          </button>
          <button
            type="submit"
            className="px-6 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition-colors"
          >
            保存
          </button>
        </div>
      </form>
    </div>
  );
}